/**
 * $.dialog
 * @extends jquery-1.10.2
 * @fileOverview 弹出层
 * @author BW
 * @email
 * @site
 * @version 0.1
 * @date 2014-2-16
 * Copyright (c) 2013-2014 BW
 * @example
 * $("#box").dialog({
move: true,
title: "添加分类",
buttons: [{
name: "重置",
callback: function() {
alert("重置");
}
}, {
name: "上一步",
callback: function() {
alert("上一步");
}
}]
}).dialog("open");
 */
(function($) {
	var dialogId = "";
	$.fn.dialog = function() {
		var method = arguments[0];
		if (methods[method]) {
			method = methods[method];
			// 我们的方法是作为参数传入的，把它从参数列表中删除，因为调用方法时并不需要它
			arguments = Array.prototype.slice.call(arguments, 1);
		} else if (typeof(method) == "object" || !method) {
			method = methods.init;
		} else {
			$.error("Method" + method + "does not exist on jQuery.dialog");
			return this;
		}
		// 用apply方法来调用我们的方法并传入参数
		return method.apply(this, arguments);
	};

	var methods = {
		init: function(options) {
			var defaults = {
				move: false,
				mask: false,
				width: "auto",
				height: "auto",
				title: false,
				//content: "url:http://localhost:8080/static/temp/dialog/content.html",
				//content: "url:content.html",
				content: "请稍候...",
				//content:"object:#div1",
				showBtn: true,
				okText: "确认",
				cancelText: "取消",
				ok: function() {},
				cancel: function() {
					if (settings.mask == true) {
						$("#" + dialogId + "-mask").remove();
					}
					methods.close();
				},
				buttons: []
			};

			var settings = $.extend({}, defaults, options);

			return this.each(function() {
				var $dialog = $(this);
				drawDialog($dialog, settings);
			});
		},
		close: function() {
			//$("#" + idName).empty().css("display", "none");
			$("#" + dialogId + "-mask").remove();
			$("#" + dialogId).remove();
		}
	};

	//画出Dialog
	function drawDialog($dialog, settings) {
		$dialog.addClass("green-ui-dialog"); //把dom加入到dialog中，并添加class
		dialogId = $dialog.attr("id");
		var isIframe = settings.content.indexOf("url:");
		var isObject = settings.content.indexOf("object:");

		//画标题BOX
		var drawTitle = function($dialog) {
			if (typeof(settings.title) == "string") { //显示标题
				var $titleBox = $("<div class=\"green-ui-dialog-titleBox\"><h3></h3><p><span>X</span></p></div>").attr("id", dialogId + "-titleBox");
				$titleBox.find("h3").text(settings.title); //找到h3标签，并设置此标签文本内容
				$titleBox.find("span").attr("id", dialogId + "-close"); //找到span标签，并设置此标签id属性
				$dialog.append($titleBox);
				$titleBox.css("line-height", $titleBox.height() + "px"); //设置div标签css行高
			}
		};

		//内容BOX
		var drawContent = function($dialog) {
			var $contentBox = $("<div class=\"green-ui-dialog-contentBox\"></div>").attr("id", dialogId + "-contentBox");
			if (isObject == -1 && isIframe == -1) { //无object前缀,无url前缀，表示直接加载文本
				var $span = $("<span></span>").text(settings.content); //设置span标签的文本内容
				$contentBox.append($span);
				$dialog.append($contentBox);
				drawButton($dialog);
				setDialog($dialog);
			} else if (isObject != -1) { //有object前缀，表示直接加载html
				var $object = $(settings.content.split("object:")[1]);
				$contentBox.width($object.width()).height($object.height());
				var $copyObj = $object.clone();
				var copyObjId = $copyObj.attr("id");
				$copyObj.attr("id", copyObjId + "-display")
				$contentBox.append($copyObj);
				$copyObj.css("display", "inline");
				$dialog.append($contentBox);
				drawButton($dialog);
				setDialog($dialog);
			} else { //有url前缀，表示直接加载iframe
				var iframeId = dialogId + "-iframeBox";
				var $iframe = $("<iframe scrolling=\"no\"></iframe>").attr({
					"id": iframeId,
					"src": settings.content.split("url:")[1]
				});
				$contentBox.append($iframe);
				$dialog.append($contentBox);
				drawButton($dialog);
				// var iframe = document.getElementById(iframeId);
				// if (iframe.attachEvent) {
				// 	iframe.attachEvent("onload", function() {
				// 		alert("Local iframe is now loaded.");
				// 	});
				// } else {
				// 	iframe.onload = function() {
				// 		var width = iframe.contentWindow.document.getElementsByTagName("div").offsetWidth;
				// 		setDialog($dialog);
				// 	};
				// }
				//alert(settings.content.split("url:")[1]);

				//此iframe标签加载完成后获取内容的宽高，并设置此标签的宽度和高度
				$iframe.load(function() {
					//var $iframeBody = $iframe.contents().find("body"); //获取iframe -> body
					//var $iframeDiv = $iframe.contents().find("div:first"); //获取iframe -> div

					//var divHeight = $iframeDiv.height(); //获取iframe div的高
					//var divWidth = $iframeDiv.width(); //获取iframe div的宽
					//alert("宽度：" + divWidth + "   高度：" + divHeight);

					//$iframeBody.height(divHeight + 2).width(divWidth + 2); //设置iframe body宽高
					//$iframe.height(divHeight + 4).width(divWidth + 4); //设置iframe宽高
					alert($(this).contents().find('div:first').width());

					setDialog($dialog); //设置dialog其他

				});
			}
		};

		//画按钮BOX
		var drawButton = function($dialog) {
			if (settings.showBtn == true) { //显示按钮组
				var $buttonBox = $("<div class=\"green-ui-dialog-buttonBox\"></div>").attr("id", dialogId + "-buttonBox");
				//把cancel和ok按钮加进buttons按钮组
				var cancel = {
					name: settings.cancelText,
					callback: settings.cancel
				};
				var ok = {
					name: settings.okText,
					callback: settings.ok
				};
				settings.buttons.unshift(cancel, ok); //把按钮加到数组最前面
				//循环添加每一个按钮到buttonBox中
				$.each(settings.buttons, function(k, v) {
					$buttonBox.append($("<p><span id=\"" + dialogId + "-btn-" + k + "\" class=\"green-ui-dialog-button\">" + v.name + "</span></p>"));
				});
				$dialog.append($buttonBox);
			}
		};

		//设置Dialog自适应宽度和高度，并居中
		var setDialog = function($dialog) {
			var width = settings.width; //取得自定义的宽度
			var height = settings.height; //取得自定义的高度
			var buttonBoxStr = "#" + dialogId + "-buttonBox";
			if (typeof(width) == "number") { //如果是个数字
				$dialog.css("width", width); //设置为dialog的宽度
			}
			if (typeof(height) == "number") { //如果是个数字
				$dialog.css("height", height); //设置为dialog的高度
				var titleBoxHeight = 0;
				var btnBoxHeight = 0;
				if (typeof(settings.title) == "string") { //如果有标题栏
					titleBoxHeight = $(titleBoxStr).height(); //取得标题栏高度
				}
				if (settings.showBtn == true) { //如果有按钮栏
					btnBoxHeight = $(buttonBoxStr).height(); //取得按钮栏高度
				}
				var contentBoxHeight = height - titleBoxHeight - btnBoxHeight - 5; //得到内容栏高度

				$("#" + dialogId + "-contentBox").css("height", contentBoxHeight + "px"); //设置内容栏高度
				//设置按钮栏为最底部
				$(buttonBoxStr).css({
					"position": "absolute",
					"bottom": "0px"
				});
			}

			var width = $dialog.width();
			var height = $dialog.height();

			//设置dialog居中
			$dialog.css({
				"display": "inline",
				"left": "50%",
				"top": "50%",
				"margin": "-" + (height / 2) + "px 0 0 -" + (width / 2) + "px",
				"width": width + "px",
				"height": height + "px",
				"z-index": "10001"
			});
		};


		//打开遮蔽层
		var drawMask = function() {
			if (settings.mask == true) {
				$("body").append($("<div id=\"" + dialogId + "-mask\" class=\"green-ui-dialog-mask\"></div>"));
				$("#" + dialogId + "-mask").addClass("green-ui-dialog-mask");
			}
		};

		//添加事件
		var bindAll = function($dialog) {
			//为title关闭按钮添加鼠标移入移出事件和click事件
			var divCloseStr = "#" + dialogId + "-close";
			var titleBoxStr = "#" + dialogId + "-titleBox";
			if (typeof(settings.title) == "string") {
				$(divCloseStr).mouseover(function() {
					$(divCloseStr).addClass("green-ui-dialog-close");
				}).mouseout(function() {
					$(divCloseStr).removeClass("green-ui-dialog-close");
				});
				$dialog.on("click", divCloseStr, function() {
					if (settings.mask == true) {
						$("#" + dialogId + "-mask").remove();
					}
					methods.close();
				});
			}

			//如果dialog可以移动，就添加移动事件
			if (settings.move == true) {
				$(titleBoxStr).mouseover(function() {
					$dialog.css("cursor", "move");
				}).mouseout(function() {
					$dialog.css("cursor", "default");
				}).mousedown(function(event) {
					$dialog.append($("<div id=\"" + dialogId + "-hide\"></div>"));
					$("#" + dialogId + "-hide").css({
						"position": "relative",
						"width": $dialog.width(),
						"height": $dialog.height() - $(titleBoxStr).height(),
						"top": "-" + ($dialog.height() - $(titleBoxStr).height()) + "px",
						"z-index": "10002"
					});
					var offset = $dialog.offset();
					var x1 = event.pageX - offset.left;
					var y1 = event.pageY - offset.top;
					var btnNum = event.which;
					if (btnNum == 1) {
						$(document).mousemove(function(event) {
							$("#" + dialogId + "-iframeBox").contents().find("p").text("x:" + event.pageX + "  y:" + event.pageY);
							$dialog.css({
								"left": (event.pageX - x1) + "px",
								"top": (event.pageY - y1) + "px",
								"margin": "0"
							});
						});
					}
				}).mouseup(function() {
					$("#" + dialogId + "-hide").remove();
					$(document).unbind("mousemove");
				});;

			}

			//为每个按钮添加鼠标移入移出事件和点击事件
			if (settings.showBtn == true) {
				$.each(settings.buttons, function(k, v) {
					var str = dialogId + "-btn-" + k;
					$("#" + str).mouseover(function() {
						$("#" + str).addClass("green-ui-dialog-button-change");
					}).mouseout(function() {
						$("#" + str).removeClass("green-ui-dialog-button-change");
					});

					$(document).on("click", "#" + str, function() {
						v.callback();
					});
				});
			}
		};

		drawTitle($dialog);
		drawContent($dialog);
		drawMask($dialog);
		bindAll($dialog);
	}

})(jQuery);